#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
	测试脚本
	D:\Git\YES-DISPLAY-TOOLS\report-filter-tool\scripts\邦定日产量\example\邦锭日产量.xlsx
	python .\make-report.py D:\Git\YES-DISPLAY-TOOLS\report-filter-tool\scripts\邦定日产量\example\邦锭日产量.xlsx D:\Git\YES-DISPLAY-TOOLS\report-filter-tool\scripts\邦定日产量\build 2021-06-01 2021-06-30
"""

# 处理传入参数
from calendar import month
import sys
# 处理文件打开
import os
# 正则表达式, 字符串模式匹配
import re
# 处理路径
# 参考: https://docs.python.org/3/library/pathlib.html
from pathlib import Path, PureWindowsPath
# 处理日期时间
from datetime import datetime

# 解析excel文件
# import xlrd
import openpyxl
from openpyxl.descriptors.base import String

import pandas as pd
import matplotlib.pyplot as plt

# constants
DATE_FORMAT = "%Y-%m-%d"

# global variables
inputxls = ""
outputfolder = ""
startdate = ""
enddate = ""
datelist = 0
valuelist = 0
ser = {0:0}
pdlist = []



def para_check():
	global inputxls
	global outputfolder
	global startdate
	global enddate

	check_result = 0
	"""
	对参数进行测试, 0是脚本身, 所以, 要从1开始测试
	"""
	# 检查参数1
	p = Path(PureWindowsPath(sys.argv[1]))
	#print(p)
	if (p.exists() == False):
		print("p1 check error")
		check_result |= (1 << 0)
	if (p.is_file() == False):
		check_result |= (1 << 0)
	inputxls = p
	print("inputxls in parachek %s" % (inputxls))

	# 检查参数2
	p = Path(PureWindowsPath(sys.argv[2]))
	#print(p)
	if (p.exists() == False):
		check_result |= (1 << 1)
	if (p.is_dir() == False):
		check_result |= (1 << 1)
	outputfolder = p

	# 检查参数3
	try:
		p3 = datetime.strptime(sys.argv[3], "%Y-%m-%d")
	except:
		print("find error")
		check_result |= (1 << 2)
	else:
		print(p3)
	startdate = p3
	# 检查参数4
	try:
		p4 = datetime.strptime(sys.argv[4], "%Y-%m-%d")
	except:
		print("find error")
		check_result |= (1 << 3)
	else:
		print(p4)
	enddate = p4

	#
	if (check_result != 0):
		return check_result
	else:
		return 0


def get_data():
	global datelist
	global valuelist
	global ser

	# https://zhuanlan.zhihu.com/p/342422919

	#print(inputxls)
	wb = openpyxl.load_workbook(inputxls, data_only=True)

	sheetnameslist = wb.sheetnames
	print(sheetnameslist)

	sheetnamethismonth = ""
	print(startdate.month)
	for i in range(len(sheetnameslist)):
		if (("%02d" % startdate.month) in sheetnameslist[i]):
			sheetnamethismonth = sheetnameslist[i]
	print(sheetnamethismonth)

	sheet = wb[sheetnamethismonth]

	cell = sheet.cell(row=4, column=4)
	print(cell.value)

	datelist = sheet['A']
	valuelist = sheet['G']

	d = {0: 0}

	pattern = re.compile(r'\d+日')
	for cell in datelist:
		#print(cell.value)
		if (type(cell.value) != type('a')):
			continue
		if (pattern.match(cell.value)):
			#print('YES')
			row = cell.row
			#print(row)
			date = cell.value

			pv = valuelist[row - 1].value
			#print(pv)
			ser.update({date:pv})

			pdlist.append(pv)

	print(ser)


	return 0


def drawpic():
	global inputxls
	global outputfolder
	global startdate
	global enddate
	global datelist
	global valuelist

	# fn = 'D:/Git/YES-DISPLAY-TOOLS/report-filter-tool/scripts/邦定日产量/example/datas.xlsx'
	# fp = Path(PureWindowsPath(fn))
	# data_source = pd.read_excel(fp)
	# # 函数plot()尝试根据数字绘制出有意义的图形
	# print(data_source['datas'])
	# plt.plot(data_source['datas'])
	# #plt.show()
	# plt.savefig('D:/Git/YES-DISPLAY-TOOLS/report-filter-tool/scripts/邦定日产量/build/datas.png')#保存图片

	fp = Path(PureWindowsPath(inputxls))
	data_source = pd.read_excel(fp, sheet_name='报表21.06')
	# 函数plot()尝试根据数字绘制出有意义的图形
	pdcount = data_source['产出数量']
	print(pdcount)
	print(type(pdcount))

	pdcount = pd.Series(pdlist)
	plt.plot(pdcount)

	#pddate = data_source['产品名称']
	#plt.plot(pddate)

	#plt.show()
	plt.savefig(
		'D:/Git/YES-DISPLAY-TOOLS/report-filter-tool/scripts/邦定日产量/build/datas.png'
	)  #保存图片

	pass


def main():
	"""
	 通过sys模块来识别参数demo, http://blog.csdn.net/ouyang_peng/
	"""
	print('参数个数为:', len(sys.argv), '个参数。')

	if (len(sys.argv) <= 1):
		print("参数1=输入文件路径")
		print("参数2=输出文件路径")
		print("参数3=开始时间")
		print("参数3=截至时间")
		return 0

	print('参数列表:', str(sys.argv))
	print('脚本名为：', sys.argv[0])
	for i in range(1, len(sys.argv)):
		print('参数 %s 为：%s' % (i, sys.argv[i]))

	# 检查输入参数
	r = para_check()
	if (r == 0):
		print("para check OK")
	else:
		print("para check ERROR")

	print("inputxls after parachek %s" % (inputxls))

	# 处理输入文件
	r = get_data()
	if (r == 0):
		print("get data OK")
	else:
		print("get data ERROR")

	# 过滤数据

	# 生成图表
	drawpic()

	# def main() end


if __name__ == "__main__":
	main()
